import pulsar
import asyncio
import time
import json
import math
from django.conf import settings

# 创建命名空间
# PUT http://api.yisbar.com:28080/admin/v2/namespaces/public/yisbar


def has_Pulsar_Conf():
    """取配置文件"""
    try:
        with open(settings.CONF / "pulsar.json", "r") as fs:
            code = fs.read()
            dictcode = json.loads(code)
    except BaseException as err:
        dictcode = None
    return dictcode


async def send_alert_queue(host, message):
    """pulsar 生产者"""
    conf = has_Pulsar_Conf()
    if not conf or not conf.get("status"):
        return
    # print(conf)
    client = pulsar.Client(f'pulsar://{conf.get("host")}:{conf.get("pport")}')
    producer = client.create_producer(
        f'persistent://public/{conf.get("namespace")}/{host}',
        producer_name="yisbar_server",
    )
    producer.send(f"{message}".encode("utf-8"))
    client.close()
    print("发送消息队列完成...")


# await send_alert_queue()
# or
# asyncio.run(send_alert_queue())


def SendAsyncMessage(pid, localdb, url, act="get"):
    """发送异步消息"""
    asyncio.run(
        send_alert_queue(
            host=f"place_{pid}",
            message={
                "url": url,
                "act": act,
                "localdb": localdb,
                "stamp": time.time(),
            },
        )
    )


def SendAsyncMessageEx(pid, types, data):
    """发送pulsar异步消息"""
    asyncio.run(
        send_alert_queue(
            host=f"place_{pid}",
            message={
                "type": types,
                "data": data,
                "stamp": ceil(time.time() * 1000),
                "bem": "",
            },
        )
    )
